import type { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import MenuAPI, { type RouteVO } from "@/api/menu";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

export const usePermissionStore = defineStore("permission", () => {
  /** 所有路由，包括静态和动态路由 */
  const routes = ref<RouteRecordRaw[]>([]);
  /** 混合模式左侧菜单 */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);

  function generateRoutesss(data: any) {
    return data.map((item) => {
      const route = {
        path: item.routePath,
        component: item.component,
        // redirect: item.redirect,
        name: item.meta.title,
        meta: item.meta,
        keepAlive: false,
        children: [],
      };

      if (item.children && item.children.length > 0) {
        route.children = generateRoutesss(item.children);
      }

      return route;
    });
  }
  /**
   * 生成动态路由
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      MenuAPI.getRoutes()
        .then((data) => {
          console.log("RouteData", data);
          data = generateRoutesss(data.result);

          console.log("data2data2", data);

          //  data =[
          //   {
          //     "path": "/system",
          //     "component": "Layout",
          //     "redirect": "/system/user",
          //     "name": "/system",
          //     "meta": {"title": "系统管理","icon": "system",},
          //     "children": [
          //       {
          //         "path": "user",
          //         "component": "system/user/index",
          //         "name": "User",
          //         "meta": {
          //           "title": "用户管理",
          //           "icon": "el-icon-User",
          //           "params": null
          //         }
          //       },
          //       {
          //         "path": "menu",
          //         "component": "system/menu/index",
          //         "name": "menu",
          //         "meta": {
          //           "title": "菜单管理",
          //           "icon": "menu",
          //           "params": null
          //         }
          //       },
          //     ]
          //   },
          // ]
          const dynamicRoutes = transformRoutes(data);

          // const dynamicRoutes = transformRoutes(data);

          routes.value = constantRoutes.concat(dynamicRoutes);
          resolve(dynamicRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: RouteVO[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmpRoute = { ...route } as RouteRecordRaw;
    // 顶级目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == "Layout") {
      tmpRoute.component = Layout;
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules["../../views/error-page/404.vue"];
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = transformRoutes(route.children);
    }

    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例
 * @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
